<template>
  <div class="app-container">
    <!-- 搜索筛选操作栏 -->
    <div class="filter-container clearfix">
      <el-button v-waves class="filter-item" @click="handleCreate">
        添加分类
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      :key="tableKey"
      ref="table"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column align="center" label="排序" prop="order" width="60" />
      <el-table-column align="center" label="分类名称" prop="name" />
      <el-table-column align="center" label="分类图片">
        <template slot-scope="{ row }">
          <el-image
            style="width:40px; height: 40px"
            :src="row.image_url"
            :preview-src-list="[row.image_url]"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" label="上级分类" prop="parent.name" />
      <el-table-column align="center" label="商品数" prop="product_num" />
      <el-table-column align="center" label="操作">
        <template slot-scope="{ row }">
          <el-button
            size="mini"
            plain
            type="primary"
            @click="handleUpdate(row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            plain
            type="danger"
            @click="handleDelete(row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加&编辑 -->
    <el-dialog
      :title="type == 0 ? '添加分类' : '编辑分类'"
      :visible.sync="dialogVisible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @closed="dialogClosed"
      width="40%"
    >
      <el-form
        ref="postForm"
        :model="form"
        :rules="rules"
        class="form-container"
      >
        <div class="createPost-main-container">
          <el-form-item label-width="90px" label="排序:" prop="order">
            <el-input v-model="form.order" class="input-spin" type="number" />
          </el-form-item>
          <el-form-item label-width="90px" label="分类名称:" prop="name">
            <el-input v-model.trim="form.name" />
          </el-form-item>
          <el-form-item label-width="90px" label="上级分类:" prop="parent_id">
            <el-select
              v-model="form.parent_id"
              :disabled="type == 1"
              placeholder="请选择上级分类"
              clearable
              style="width: 100%;"
            >
              <el-option
                v-for="(item, index) in parentClassifyOptions"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label-width="90px" label="分类图片:" prop="image_url">
            <el-upload
              :file-list="fileList"
              action="#"
              :limit="1"
              accept=".jpg,.jpeg,.png,.JPG,.JPEG"
              list-type="picture-card"
              :http-request="
                file => {
                  return uploadImgHandle(file);
                }
              "
              :on-remove="
                (file, fileList) => {
                  return removeHandle(file, fileList);
                }
              "
              :class="{ hide: fileList.length > 0 }"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
      <div style="margin-top: 40px;text-align: center;">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleToggleEdit">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getClassify,
  getParentClassify,
  deleteClassify,
  createClassify,
  updateClassify,
  uploadFile
} from "@/api/common";
import waves from "@/directive/waves"; // waves directive

export default {
  name: "auctionGoodClassify",
  directives: {
    waves
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      listLoading: true,
      dialogVisible: false,
      type: 0,
      fileList: [],
      parentClassifyOptions: [],
      form: {
        order: undefined,
        name: undefined,
        parent_id: undefined,
        image_url: undefined
      },
      rules: {
        order: [
          {
            required: true,
            message: "请输入排序",
            trigger: "blur"
          }
        ],
        name: [
          {
            required: true,
            message: "请输入分类名称",
            trigger: "blur"
          }
        ],
        parent_id: [
          {
            required: true,
            message: "请选择上级分类",
            trigger: "change"
          }
        ],
        image_url: [
          {
            required: true,
            message: "请上传图片",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getParentList();
    this.getList();
  },
  methods: {
    removeHandle() {
      this.form.image_url = undefined;
      this.fileList = [];
    },
    uploadImgHandle(e) {
      let formData = new FormData();
      formData.append("file", e.file);
      uploadFile(formData).then(res => {
        const image = res.data;
        this.fileList = [
          {
            url: this.$store.state.settings.imgHost + image
          }
        ];
        this.form.image_url = image;
      });
    },
    getParentList() {
      getParentClassify().then(res => {
        this.parentClassifyOptions = res.data;
        this.parentClassifyOptions.unshift({ id: 0, name: "作为一级分类" });
      });
    },
    getList() {
      this.listLoading = true;
      getClassify()
        .then(response => {
          this.list = response.data || [];
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    // 编辑
    handleUpdate(row) {
      this.type = 1;
      this.form = Object.assign({}, row);
      this.fileList = [
        {
          url: this.$store.state.settings.imgHost + row.image_url
        }
      ];
      this.dialogVisible = true;
    },
    // 新增
    handleCreate() {
      this.type = 0;
      this.dialogVisible = true;
    },
    dialogClosed() {
      this.form = {
        order: undefined,
        name: undefined,
        parent_id: undefined,
        image_url: undefined
      };
      this.fileList = [];
      this.$refs["postForm"].resetFields();
    },
    // 处理新增||处理编辑
    handleToggleEdit() {
      this.$refs.postForm.validate(async valid => {
        if (valid) {
          this.listLoading = true;
          if (this.type == 0) {
            createClassify(this.form)
              .then(() => {
                this.$notify({
                  title: "提示",
                  message: "新增成功",
                  type: "success",
                  duration: 2000
                });
                this.dialogVisible = false;
                this.getList();
              })
              .catch(() => {
                this.listLoading = false;
              });
          } else {
            updateClassify(this.form["id"], this.form)
              .then(() => {
                this.$notify({
                  title: "提示",
                  message: "编辑成功",
                  type: "success",
                  duration: 2000
                });
                this.dialogVisible = false;
                this.getList();
              })
              .catch(() => {
                this.listLoading = false;
              });
          }
        }
      });
    },
    // 删除
    handleDelete(id) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.listLoading = true;
          deleteClassify(id)
            .then(res => {
              this.listLoading = false;
              if (res.code == 200) {
                this.$notify({
                  title: "提示",
                  message: "删除成功",
                  type: "success",
                  duration: 2000
                });
                this.getList();
              } else {
                this.$notify({
                  title: "提示",
                  message: res.msg || "删除失败",
                  type: "error",
                  duration: 2000
                });
              }
            })
            .catch(err => {
              this.listLoading = false;
            });
        })
        .catch(() => {});
    }
  }
};
</script>

<style>
.el-upload-list__item.is-ready,
.el-upload-list__item.is-uploading {
  display: none !important;
}

.hide .el-upload--picture-card {
  display: none;
}

.el-upload-list__item {
  transition: none !important;
}
</style>
